package com.kye.express.business.waybill_list.subfragment;

import com.kye.base.utils.DateUtils;
import com.kye.express.contract.base.BasePresenter;
import com.kye.express.contract.base.view.ErrorView;
import com.kye.express.contract.base.view.IView;
import com.kye.express.contract.base.view.LoadingView;
import com.kye.model.OpenApiResultObserver;
import com.kye.model.UserSession;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.OpenApiResult;
import com.kye.model.bean.logistics.LogisticsListResultBean;
import com.kye.model.bean.logistics.LogisticsUrgeResultBean;
import com.kye.model.bean.logistics.request.RequestLogisticsList;
import com.kye.model.bean.logistics.request.RequestLogisticsUrge;
import com.kye.model.bean.logistics.request.RequestPostLogisticsUrgeMessage;
import com.kye.model.bean.user.User;
import com.kye.model.datasource.LogisticsDataSource;

import java.util.Date;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public interface WayBillListToSignContract {

    interface WayBillListToSignView extends IView, LoadingView, ErrorView {

        void onUser(User user);

        void refreshInitSuccess(OpenApiResult<LogisticsListResultBean> result, LogisticsListResultBean logisticsListResultBean);

        void refreshInitFailed(String msg);

        void refreshInitFailed(Throwable e);

        void refreshSuccess(LogisticsListResultBean logisticsListResultBean);

        void refreshFailed(String msg);

        void refreshFailed(Throwable e);

        void loadMoreSuccess(LogisticsListResultBean logisticsListResultBean);

        void loadMoreFailed(String msg);

        void loadMoreFailed(Throwable e);

        void postWayBillUrgeSuccess(LogisticsUrgeResultBean logisticsUrgeResultBean);

        void postWayBillUrgeMessageSuccess();

    }

    class WayBillListToSignPresenter extends BasePresenter<WayBillListToSignView> {

        private LogisticsDataSource logisticsDataSource;
        private Observable<User> userObservable;
        private User userInfo;
        private PageInfo pageInfo;

        public WayBillListToSignPresenter() {
            logisticsDataSource = new LogisticsDataSource();
        }

        @Override
        public void bind(WayBillListToSignView view) {
            super.bind(view);
            pageInfo = new PageInfo();
            userObservable = UserSession.getInstance().getUserForRx()
                    .compose(getView().bindToLifecycleDestroy())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread());
        }

        public void refreshInit() {
            Single.just(new RequestLogisticsList())
                    .doOnSuccess(new Consumer<RequestLogisticsList>() {
                        @Override
                        public void accept(RequestLogisticsList requestLogisticsList) throws Exception {
                            requestLogisticsList.setPhone(userInfo.getPhone());
                            requestLogisticsList.setOrderMan(userInfo.getUserName());
                            requestLogisticsList.setStartTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setEndTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setPageIndex(PageInfo.INDEX_DEFAULT);
                            requestLogisticsList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestLogisticsList.setQueryState("0");
                        }
                    })
                    .flatMap(new Function<RequestLogisticsList, SingleSource<OpenApiResult<LogisticsListResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<LogisticsListResultBean>> apply(RequestLogisticsList requestLogisticsList) throws Exception {
                            return logisticsDataSource
                                    .getLogisticsList(requestLogisticsList)
                                    .compose(getView().<OpenApiResult<LogisticsListResultBean>>bindToLifecycleDestroy());
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<LogisticsListResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<LogisticsListResultBean> result, LogisticsListResultBean logisticsListResultBean) {
                            pageInfo.resetPage();
                            getView().refreshInitSuccess(result, logisticsListResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<LogisticsListResultBean> result, int code, String msg) {
                            getView().refreshInitFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshInitFailed(e);
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        public void refresh() {
            Single.just(new RequestLogisticsList())
                    .doOnSuccess(new Consumer<RequestLogisticsList>() {
                        @Override
                        public void accept(RequestLogisticsList requestLogisticsList) throws Exception {
                            requestLogisticsList.setPhone(userInfo.getPhone());
                            requestLogisticsList.setOrderMan(userInfo.getUserName());
                            requestLogisticsList.setStartTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setEndTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setPageIndex(PageInfo.INDEX_DEFAULT);
                            requestLogisticsList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestLogisticsList.setQueryState("0");
                        }
                    })
                    .flatMap(new Function<RequestLogisticsList, SingleSource<OpenApiResult<LogisticsListResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<LogisticsListResultBean>> apply(RequestLogisticsList requestLogisticsList) throws Exception {
                            return logisticsDataSource
                                    .getLogisticsList(requestLogisticsList)
                                    .compose(getView().<OpenApiResult<LogisticsListResultBean>>bindToLifecycleDestroy());
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<LogisticsListResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<LogisticsListResultBean> result, LogisticsListResultBean logisticsListResultBean) {
                            pageInfo.resetPage();
                            getView().refreshSuccess(logisticsListResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<LogisticsListResultBean> result, int code, String msg) {
                            getView().refreshFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().refreshFailed(e);
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        public void loadMore() {
            Single.just(new RequestLogisticsList())
                    .doOnSuccess(new Consumer<RequestLogisticsList>() {
                        @Override
                        public void accept(RequestLogisticsList requestLogisticsList) throws Exception {
                            requestLogisticsList.setPhone(userInfo.getPhone());
                            requestLogisticsList.setOrderMan(userInfo.getUserName());
                            requestLogisticsList.setStartTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setEndTime(DateUtils.getDateStringByDateYearMonthDay(new Date()));
                            requestLogisticsList.setPageIndex(pageInfo.getPageIndex() + 1);
                            requestLogisticsList.setPageSize(PageInfo.SIZE_DEFAULT);
                            requestLogisticsList.setQueryState("0");
                        }
                    })
                    .flatMap(new Function<RequestLogisticsList, SingleSource<OpenApiResult<LogisticsListResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<LogisticsListResultBean>> apply(RequestLogisticsList requestLogisticsList) throws Exception {
                            return logisticsDataSource
                                    .getLogisticsList(requestLogisticsList)
                                    .compose(getView().<OpenApiResult<LogisticsListResultBean>>bindToLifecycleDestroy());
                        }
                    })
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<LogisticsListResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {

                        }

                        @Override
                        public void onSuccess(OpenApiResult<LogisticsListResultBean> result, LogisticsListResultBean logisticsListResultBean) {
                            pageInfo.increasePage();
                            getView().loadMoreSuccess(logisticsListResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<LogisticsListResultBean> result, int code, String msg) {
                            getView().loadMoreFailed(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().loadMoreFailed(e);
                        }

                        @Override
                        public void onLoaded() {

                        }
                    });
        }

        /**
         * 待签收的崔健
         *
         * @param waybill
         * @param userInfo
         */
        public void postWaybillUrge(String waybill, User userInfo) {
            Single.just(new RequestLogisticsUrge())
                    .doOnSuccess(new Consumer<RequestLogisticsUrge>() {
                        @Override
                        public void accept(RequestLogisticsUrge requestLogisticsUrge) throws Exception {
                            requestLogisticsUrge.setPhone(userInfo.getPhone());
                            requestLogisticsUrge.setSource("APP");
                            requestLogisticsUrge.setType("1"); // 类型（0 取 1派）
                            requestLogisticsUrge.setWaybill(waybill);
                        }
                    })
                    .flatMap(new Function<RequestLogisticsUrge, SingleSource<OpenApiResult<LogisticsUrgeResultBean>>>() {
                        @Override
                        public SingleSource<OpenApiResult<LogisticsUrgeResultBean>> apply(RequestLogisticsUrge requestLogisticsUrge) throws Exception {
                            return logisticsDataSource
                                    .postLogisticsUrge(requestLogisticsUrge)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<LogisticsUrgeResultBean>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<LogisticsUrgeResultBean> result, LogisticsUrgeResultBean logisticsUrgeResultBean) {
                            getView().postWayBillUrgeSuccess(logisticsUrgeResultBean);
                        }

                        @Override
                        public void onApiError(OpenApiResult<LogisticsUrgeResultBean> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        /**
         * 发送留言
         *
         * @param urgeMessage
         */
        public void postWaybillUrgeMessage(String urgeMessage, User userInfo, String waybill) {
            Single.just(new RequestPostLogisticsUrgeMessage())
                    .doOnSuccess(new Consumer<RequestPostLogisticsUrgeMessage>() {
                        @Override
                        public void accept(RequestPostLogisticsUrgeMessage requestPostLogisticsUrgeMessage) throws Exception {
                            requestPostLogisticsUrgeMessage.setPhone(userInfo.getPhone());
                            requestPostLogisticsUrgeMessage.setRemark(urgeMessage);
                            requestPostLogisticsUrgeMessage.setWaybill(waybill);
                        }
                    })
                    .flatMap(new Function<RequestPostLogisticsUrgeMessage, SingleSource<OpenApiResult<Object>>>() {
                        @Override
                        public SingleSource<OpenApiResult<Object>> apply(RequestPostLogisticsUrgeMessage requestPostLogisticsUrgeMessage) throws Exception {
                            return logisticsDataSource
                                    .postLogisticsUrgeMessage(requestPostLogisticsUrgeMessage)
                                    .compose(getView().bindToLifecycleDestroy());
                        }
                    })
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new OpenApiResultObserver<Object>() {
                        @Override
                        public void onLoading(Disposable d) {
                            getView().onLoading();
                        }

                        @Override
                        public void onSuccess(OpenApiResult<Object> result, Object o) {
                            getView().postWayBillUrgeMessageSuccess();
                        }

                        @Override
                        public void onApiError(OpenApiResult<Object> result, int code, String msg) {
                            getView().onError(msg);
                        }

                        @Override
                        public void onOtherError(Throwable e) {
                            getView().onError(e.getMessage());
                        }

                        @Override
                        public void onLoaded() {
                            getView().onLoaded();
                        }
                    });
        }

        public void getUserInfo() {
            userObservable
                    .subscribe(new Consumer<User>() {
                        @Override
                        public void accept(User user) throws Exception {
                            userInfo = user;
                            getView().onUser(user);
                        }
                    });
        }

        public Observable<User> getUserObservable() {
            return userObservable;
        }

        public User getUser() {
            return userInfo;
        }
    }

}
